﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SewerAPI.Core;
using System.Net.Sockets;
using SewerAPI.Util;

namespace SewerAPI.IO
{
    /// <summary>
    /// Class to send sewer messages
    /// </summary>
    public class Server : TransactionHandler, IDisposable
    {
        #region Private Fields

        UdpClient client;

        #endregion

        #region Public Fields



        #endregion

        public Server() : base()
        {
            
        }

        #region Abstract Methods

        protected override void PerformTransaction(Message m)
        {
            byte[] _dgram = Message.Encrypt(m);
            client.Send(_dgram, _dgram.Length, m.To);
        }

        protected override void InitializeHandler()
        {
            SewerLogger.Instance.Debug("Opening UDP client on port {0}", Configuration.Port);
            client = new UdpClient();
            //client.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.ReuseAddress, true);
            client.EnableBroadcast = true;
        }

        #endregion

        /// <summary>
        /// Close the port to avoid concurrency
        /// </summary>
        public void Dispose()
        {
            if (client != null)
            {
                try { client.Close(); }
                catch { }
            }
        }
    }
}
